package com.app.business.web.business;

import com.app.business.en.HouseStatus;
import com.app.business.en.Status;
import com.app.business.model.AzProject;
import com.app.business.model.House;
import com.app.business.service.AzProjectService;
import com.app.business.service.HouseService;
import com.app.system.jpa.PageBean;
import com.app.system.log4j2.LogUtils;
import com.app.system.permission.model.DataDict;
import com.app.system.permission.service.DataDictService;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.WebUtils;
import com.app.system.utils.dataType.BigDecimalUtils;
import com.app.system.utils.dataType.DateUtils;
import com.app.system.utils.dataType.IntegerUtils;
import com.app.system.utils.dataType.StringUtils;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.app.system.utils.page.LayUiUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import freemarker.template.Configuration;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.*;

/**
 * 住宅房源管理
 * Created by lsh on 2019/2/11 14:49.
 *
 * @author lsh
 */
@Controller
@RequestMapping("/business/house/*")
@SuppressWarnings("all")
public class HouseController {

    @Resource
    private HouseService houseService;
    @Resource
    private DataDictService dataDictService;
    @Resource
    private AzProjectService azProjectService;
    private Logger logger = LogUtils.getBusinessLogger();

    @Autowired
    private Configuration freemarkerConfiguration; // 注入bean，这里是属性注入，推荐构造注入

    /**
     * 住宅房源数据管理列表
     */
    @RequestMapping("houseList")
    @RequiresPermissions("house:houseList")
    public void houseList(HttpServletRequest request, ModelMap modelMap) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        AzProject azProject = this.azProjectService.findOne(projectId);
        modelMap.addAttribute("azProject", azProject);
    }

    /**
     * 加载房源信息数据
     *
     * @return
     */
    @RequestMapping("loadHouseList")
    @ResponseBody
    @RequiresPermissions("house:loadHouseList")
    public Map loadHouseList(HttpServletRequest request) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        List<Map> listData = Lists.newArrayList();
        PageBean<House> housePageBean = this.houseService.houseListByProjectId(projectId);
        List<House> houseList = housePageBean.getDatas();
        Map<String, DataDict> houseTypeMap = this.dataDictService.getMapByParentNameForValue("房屋类型");
        Map<String, DataDict> houseStatusMap = this.dataDictService.getMapByParentNameForValue("房源状态");
        Map<String, DataDict> houseHoldMap = this.dataDictService.getMapByParentNameForValue("房屋户型");
        if (!CollectionUtils.isEmpty(houseList)) {
            Map<String, Object> item = null;
            for (House house : houseList) {
                item = null;
                item = Maps.newHashMap();
                item.put("id", house.getId());
                item.put("buildNum", StringUtils.getNotNull(house.getBuildNum()));
                item.put("houseNum", StringUtils.getNotNull(house.getHouseNum()));
                item.put("floor", house.getFloor());
                item.put("houseTypeStr", StringUtils.dataDictShow(houseTypeMap.get(house.getHouseType())));
                item.put("houseHoldStr", StringUtils.dataDictShow(houseHoldMap.get(house.getHouseHold())));
                item.put("propertyArea", BigDecimalUtils.getNotNullStr(house.getPropertyArea()));
                item.put("poolArea", BigDecimalUtils.getNotNullStr(house.getPoolArea()));
                item.put("houseStatus", house.getHouseStatus());
                item.put("houseStatusStr", StringUtils.dataDictShow(houseStatusMap.get(house.getHouseStatus().toString())));
                item.put("chooseHouseDate", DateUtils.dateToStringDefault(house.getChooseHouseDate()));
                listData.add(item);
            }
        }
        return LayUiUtils.page(housePageBean.getTotalCount().intValue(), listData);
    }

    /**
     * 房源信息导出
     */
    @RequestMapping("houseListExcel")
    @RequiresPermissions("house:houseListExcel")
    public void houseListExcel(HttpServletRequest request, HttpServletResponse response) {
        PageBean<House> housePageBean = this.houseService.houseExcelListByProjectId();
        List<House> houseList = housePageBean.getDatas();
        Map<String, DataDict> houseHoldMap = this.dataDictService.getMapByParentNameForValue("房屋户型");
        Map<String, DataDict> houseTypeMap = this.dataDictService.getMapByParentNameForValue("房屋类型");
        Map<String, DataDict> houseStatusMap = this.dataDictService.getMapByParentNameForValue("房源状态");
        try {
            // 封装导出数据
            Map data = Maps.newHashMap();
            data.put("houseList", houseList);
            data.put("houseHoldMap", houseHoldMap);
            data.put("houseTypeMap", houseTypeMap);
            data.put("houseStatusMap", houseStatusMap);
            data.put("exportPerson", SecurityUtils.getSubject().getPrincipal());   //导出人姓名
            data.put("exportTime", DateUtils.dateToStringFormat(new Date(), "yyyy-MM-dd HH:mm:ss"));   //导出时间
//            data.put("decisions", exportDecisionList); //第二个worksheet的数据对象
            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(("房源数据导出.xls").getBytes(), "iso-8859-1"));
            freemarkerConfiguration.getTemplate("/business/house/houseListExcel.ftl").process(data, response.getWriter());
        } catch (Exception e) {
            logger.error("文件下载异常", e);
            e.printStackTrace();
        }
    }


    /**
     * 住宅房源管理
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("houseForm")
    @RequiresPermissions("house:houseForm")
    public void houseForm(HttpServletRequest request, ModelMap modelMap) {
        Integer houseId = ParamUtils.getInt(request, "houseId", 0);
        Integer azProjectId = ParamUtils.getInt(request, "azProjectId", 0);

        House house = this.houseService.findOne(houseId);
        AzProject azProject = azProjectService.findOne(azProjectId);
        house = house == null ? new House() : house;
        Precondition.checkSqdsArguement(azProject != null, "找不到所属安置项目！");

        modelMap.addAttribute("house", house);
        modelMap.addAttribute("azProject", azProject);
    }


    /**
     * 房源信息保存
     *
     * @param request
     * @return
     */
    @RequestMapping("houseSave")
    @ResponseBody
    @RequiresPermissions("house:houseSave")
    public Response houseSave(HttpServletRequest request) {
        Integer houseId = ParamUtils.getInt(request, "houseId", 0);
        Integer azProjectId = ParamUtils.getInt(request, "azProjectId", 0);
        House house = houseService.findOne(houseId);
        AzProject project = azProjectService.findOne(azProjectId);
        Precondition.checkAjaxArguement(project != null, "0012", "项目不存在");

        if (house == null) {
            house = new House();
        }
        WebUtils.bind(request, house);
        house.setAzProject(project);
        houseService.save(house);

        Response response = new Response();
        response.setCode("0001");
        response.setData(project.getId());
        return response;
    }


    /**
     * 删除住宅房源
     *
     * @param request
     * @return
     */
    @RequestMapping("deleteHouse")
    @ResponseBody
    @RequiresPermissions("house:deleteHouse")
    public Response deleteHouse(HttpServletRequest request) {
        Integer houseId = ParamUtils.getInt(request, "houseId", 0);
        House house = houseService.findOne(houseId);
        Precondition.checkAjaxArguement(house != null, "1111", "数据错误！");
        Precondition.checkAjaxArguement(house.getHouseStatus() != null && house.getHouseStatus() != 2, "1111", "房源已选择，不可删除！");
        this.houseService.delete(house.getId());
        return new Response("0001", "操作成功");
    }

    /**
     * 导入页面
     *
     * @param request
     * @param modelMap
     */

    @RequestMapping("importPage")
    @RequiresPermissions("house:importPage")
    public void importPage(HttpServletRequest request, ModelMap modelMap) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        AzProject azProject = this.azProjectService.findOne(projectId);
        Precondition.checkAjaxArguement(azProject != null, "9999", "导入的安置项目不存在");
        Map<String, String> houseTypeMap = this.dataDictService.getMapByParentNameForName_Value("房屋类型");
        modelMap.addAttribute("azProject", azProject);
        modelMap.addAttribute("houseTypeMap", houseTypeMap);
    }


    /**
     * 导入房源数据
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Transactional
    @RequestMapping("importHouse")
    @ResponseBody
    @RequiresPermissions("house:importHouse")
    public Response importHouse(HttpServletRequest request) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        AzProject azProject = this.azProjectService.findOne(projectId);
        Precondition.checkAjaxArguement(azProject != null, "9999", "导入的安置项目不存在");
        Map<String, DataDict> houseTypeMap = this.dataDictService.getMapByParentNameForName("房屋类型");

        String houses = request.getParameter("houseArray");
        String[] houseArray = houses.split("\r\n");


        //Set<安置项目-幢号-户号-所在层数>
        Set<String> houseSet = this.houseService.findHouseSetByAzProjectId(azProject.getId());

        //buildNum:幢号，houseNum:户号，floor：所在层数，houseType：房屋类型，houseHold：户型：propertyArea：套内建筑面积，poolArea：公摊面积，galleryArea：阳台面积，sealGalleryCount：封闭阳台数量，nonSealGalleryCount：非封闭阳台数量，houseState：房源状态，memo:备注
        String buildNum = null, houseNum = null, floor = null, houseType = null, houseHold = null, propertyArea = null, poolArea = null, galleryArea = null, sealGalleryCount = null, nonSealGalleryCount = null, houseState = null, memo = null, kkgArea = null;

        House house = null;
        //待导入的房源数据
        List<House> importHouseList = new ArrayList<>();

        String[] rowObj = null;
        String excelHouse = null;
        StringBuffer msg = new StringBuffer();//错误信息
        int errorCount = 0;//错误数据数量
        int rowObjLength = 0;//每条数据的列数
        int index = 0;
        for (String houseInfo : houseArray) {
            rowObj = null;
            rowObj = houseInfo.split("\t");
            rowObjLength = rowObj.length;
            Precondition.checkAjaxArguement(rowObjLength == 13, "0013", "请确认每列都有数据！");
            if (rowObj.length == 0) {
                continue;
            }

            index = 0;
            buildNum = rowObj[index]; //幢号
            index++;
            houseNum = rowObj[index]; //户号
            index++;
            floor = rowObj[index]; //所在层数
            index++;
            houseType = rowObj[index]; //房屋类型
            index++;
            houseHold = rowObj[index]; //户型
            index++;
            propertyArea = rowObj[index]; //套内建筑面积
            index++;
            poolArea = rowObj[index]; //公摊面积
            index++;
            galleryArea = rowObj[index]; //阳台面积
            index++;
            sealGalleryCount = rowObj[index]; //封闭阳台数量
            index++;
            nonSealGalleryCount = rowObj[index]; //非封闭阳台数量
            index++;
            houseState = rowObj[index]; //户型状态
            index++;
            memo = rowObj[index];//备注
            index++;
            kkgArea = rowObj[index];//可扩改建筑面积

            excelHouse = projectId + "-" + buildNum + "-" + houseNum + "-" + floor;

            if (StringUtils.isEmpty(excelHouse)) {
                continue;
            }
            //只导入不存在的房源
            if (houseSet.contains(excelHouse)) {
                errorCount++;
                msg.append("<br/>" + houseInfo + ",");
                //已经存在的数据输出到页面
                continue;
            }

            house = new House();
            house.setAzProject(azProject);
            house.setBuildNum(buildNum);
            house.setHouseNum(houseNum);
            house.setFloor(Integer.valueOf(floor));
            house.setHouseType(houseType);
            house.setHouseHold(houseHold);
            house.setHouseStatus(houseState != null && !houseState.equals("") ? IntegerUtils.stringToInteger(houseState) : Status.NO.getIndex());

            house.setPropertyArea(BigDecimalUtils.stringToBigDecimal(propertyArea));
            house.setPoolArea(BigDecimalUtils.stringToBigDecimal(poolArea));
            house.setGalleryArea(BigDecimalUtils.stringToBigDecimal(galleryArea));
            house.setSealGalleryCount(IntegerUtils.stringToInteger(sealGalleryCount));
            house.setNonSealGalleryCount(IntegerUtils.stringToInteger(nonSealGalleryCount));
            house.setMemo(memo);
            house.setKkgArea(BigDecimalUtils.stringToBigDecimal(kkgArea));

            importHouseList.add(house);
        }
        this.houseService.batchSave(importHouseList);
        String successInfo = "插入" + importHouseList.size() + "条数据;";
        if (errorCount > 0) {
            successInfo = successInfo + "失败" + errorCount + "条，如下";
        }
        msg = msg.length() == 0 ? msg : msg.replace(0, msg.length(), msg.toString()).append("<br/>数据已存在，无法导入");
        System.out.println(successInfo + msg.toString());
        Response response = new Response("0001", successInfo + msg.toString());
        return response;

    }

    /**
     * 安置房源销控
     */
    @RequestMapping("houseTree")
    @RequiresPermissions("house:houseTree")
    public void housePicture(ModelMap modelMap) {
        List<DataDict> dataDictList = dataDictService.findListByParentName("房源状态");
        modelMap.addAttribute("dataDictList", dataDictList);
    }

    //获取树形菜单
    @RequestMapping("loadTreeData")
    @ResponseBody
    @RequiresPermissions("house:loadTreeData")
    public Map loadTreeData() {

        List<Map> childrenList = this.houseService.mapTreeData();
        Map map = Maps.newLinkedHashMap();
        map.put("id", null);
        map.put("name", "安置项目");
        map.put("spread", true);
        map.put("children", childrenList);

        return map;
    }

    //加载楼盘图
    @RequestMapping("loadHousePicture")
    @ResponseBody
    @RequiresPermissions("house:loadHousePicture")
    public Map loadHousePicture(HttpServletRequest request) {
        Integer azProjectId = ParamUtils.getInt(request, "azProjectId", 0);
        String buildNum = ParamUtils.getString(request, "buildNum", "");
        //查出所有房源
        List<House> houseList = houseService.houseList(azProjectId, buildNum);

        //得到层号和当前楼层的List<House>对应的map
        Map<String, List<House>> floorHouseMap = houseService.getFloorHouseMap(houseList);

        //房源状态
        Map<String, String> colorMap = this.dataDictService.getMapByParentNameForValue_Color("房源状态");

        //房屋类型
        Map<String, String> houseHoldMap = this.dataDictService.getMapByParentNameForValue_Name("房屋户型");

        Map<String, Integer> maxFloorMap = houseService.getMaxFloorMap(azProjectId, buildNum);
        Integer maxFloor = maxFloorMap.get("maxFloor");

        AzProject azProject = azProjectService.findOne(azProjectId);

        Map<String, Object> map = Maps.newHashMap();
        map.put("maxFloor", maxFloor);
        map.put("floorHouseMap", floorHouseMap);
        map.put("colorMap", colorMap);
        map.put("houseHoldMap", houseHoldMap);
        map.put("azProject", azProject);
        return map;
    }


    /**
     * 修改房源状态
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("updateHouseStatus")
    @RequiresPermissions("house:updateHouseStatus")
    public void updateHouseStatus(HttpServletRequest request, ModelMap modelMap) {
        Integer houseId = ParamUtils.getInt(request, "houseId", 0);
        House house = this.houseService.findOne(houseId);
        Precondition.checkSqdsArguement(house != null, "修改房源不存在");
        Precondition.checkSqdsArguement(house.getHouseStatus() != HouseStatus.YIXUAN.getIndex(), "房源已被选择，无法修改");
        modelMap.addAttribute("house", house);

        //房源状态
        List<DataDict> dataDictList = this.dataDictService.findListByParentName("房源状态");
        modelMap.addAttribute("dataDictList", dataDictList);
    }

    /**
     * 房源信息保存
     *
     * @param request
     * @return
     */
    @RequestMapping("saveHouseStatus")
    @ResponseBody
    @RequiresPermissions("house:saveHouseStatus")
    public Response saveHouseStatus(HttpServletRequest request) {
        Integer houseId = ParamUtils.getInt(request, "houseId", 0);
        Integer houseStatus = ParamUtils.getInt(request, "houseStatus", 0);
        House house = houseService.findOne(houseId);
        Precondition.checkAjaxArguement(house != null, "0012", "修改的房源不存在");
        Precondition.checkSqdsArguement(house.getHouseStatus() != HouseStatus.YIXUAN.getIndex(), "房源已被选择，无法修改");

        house.setHouseStatus(houseStatus);
        houseService.save(house);

        Response response = new Response();
        response.setCode("0001");
        Map<String, String> map = new HashMap<>();
        map.put("azProjectId", String.valueOf(house.getAzProject().getId()));
        map.put("buildNum", house.getBuildNum());
        response.setData(map);
        return response;
    }
}

